package com.tuju.currency.network;

import android.util.Log;

import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;

import retrofit2.HttpException;
import rx.Subscriber;

/**
 * Created by 彦泽 on 2018/7/26.
 */

public abstract class DefaultSubscriber<T> extends Subscriber<T> {
    @Override
    public void onCompleted() {
    }

    @Override
    public void onError(Throwable e) {
        String errorMessage;
        if (e instanceof HttpException) {     //   HTTP错误
            errorMessage = "HTTP错误";
        } else if (e instanceof ConnectException
                || e instanceof UnknownHostException) {   //   连接错误
            errorMessage = "网络错误";
        } else if (e instanceof InterruptedIOException) {   //  连接超时
            errorMessage = "链接超时";
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {   //  解析错误
            errorMessage = "解析错误：" + e.getMessage();
        } else {
            errorMessage = e.getMessage();
        }
        Log.e("yanze", "onError: " + e.getMessage());
        _onError(errorMessage);
    }

    @Override
    public void onNext(T t) {
        try {
            _onNext(t);
        } catch (IOException e) {
            _onError(e.getMessage());
            e.printStackTrace();
        }
    }

    public abstract void _onError(String errMsg);

    public abstract void _onNext(T entity) throws IOException;
}
